<template>
  <view class="container">
    <!-- 状态栏占位 -->
    <view :style="{ height: statusBarHeight + 'px' }"></view>
    
    <!-- 商家信息区域 -->
    <view class="merchant-info-section">
      <view class="merchant-info">
        <image 
          class="avatar" 
          :src="userStore.isLoggedIn ? (BASE_URL+userStore.userInfo.avatar || '/static/merchant-placeholder.png') : '/static/merchant-placeholder.png'" 
          mode="aspectFill"
        ></image>
        <view class="merchant-detail">
          <!-- 已登录显示商家信息 -->
          <template v-if="userStore.isLoggedIn && userStore.isMerchant()">
            <view class="merchant-name">{{ userStore.userInfo.shopName || '我的店铺' }}</view>
            <view class="merchant-id">{{ userStore.userInfo.phone ? `联系电话: ${maskPhone(userStore.userInfo.phone)}` : `商家ID: ${userStore.userInfo.id}` }}</view>
            <view class="merchant-detail-btn" @click="showMerchantDetail">查看详细信息</view>
          </template>
          <!-- 未登录或非商家显示登录按钮 -->
          <template v-else>
            <view class="login-btn" @click="handleLogin">商家登录</view>
            <view class="register-btn" @click="showRegisterModal">商家注册</view>
            <view class="merchant-desc">登录后管理您的店铺</view>
          </template>
        </view>
      </view>
      <view class="merchant-stats">
        <view class="stat-item">
          <text class="stat-num">{{ merchantData.orderCount }}</text>
          <text class="stat-label">订单数</text>
        </view>
        <view class="stat-item">
          <text class="stat-num">{{ merchantData.productCount }}</text>
          <text class="stat-label">商品数</text>
        </view>
        <view class="stat-item">
          <text class="stat-num">{{ merchantData.revenue }}</text>
          <text class="stat-label">收入(元)</text>
        </view>
      </view>
    </view>
       
    <!-- 订单管理 -->
    <view class="order-section">
      <view class="section-header">
        <text class="section-title">订单管理</text>
        <view class="view-all" @click="viewAllOrders">
          <text>查看全部</text>
          <uni-icons type="right" size="14" color="#999"></uni-icons>
        </view>
      </view>
      <view class="order-types">
        <view class="order-type-item" @click="viewOrderByType('new')">
          <uni-icons type="notification" size="28" color="#FF8C42"></uni-icons>
          <text>新订单</text>
          <view v-if="merchantData.newOrderCount > 0" class="badge">{{ merchantData.newOrderCount }}</view>
        </view>
        <view class="order-type-item" @click="viewOrderByType('processing')">
          <uni-icons type="spinner" size="28" color="#FF8C42"></uni-icons>
          <text>处理中</text>
        </view>
        <view class="order-type-item" @click="viewOrderByType('shipping')">
          <uni-icons type="car" size="28" color="#FF8C42"></uni-icons>
          <text>配送中</text>
        </view>
        <view class="order-type-item" @click="viewOrderByType('completed')">
          <uni-icons type="checkbox-filled" size="28" color="#FF8C42"></uni-icons>
          <text>已完成</text>
        </view>
        <view class="order-type-item" @click="viewOrderByType('refund')">
          <uni-icons type="refresh" size="28" color="#FF8C42"></uni-icons>
          <text>退款/售后</text>
        </view>
      </view>
    </view>
       
    <!-- 店铺管理 -->
    <view class="service-section">
      <view class="section-header">
        <text class="section-title">店铺管理</text>
      </view>
      <view class="service-grid">
        <view class="service-item" @click="goToService('products')">
          <uni-icons type="shop" size="24" color="#FF8C42"></uni-icons>
          <text>商品管理</text>
        </view>
        <view class="service-item" @click="goToService('promotion')">
          <uni-icons type="gift" size="24" color="#FF8C42"></uni-icons>
          <text>促销活动</text>
        </view>
        <view class="service-item" @click="goToService('finance')">
          <uni-icons type="wallet" size="24" color="#FF8C42"></uni-icons>
          <text>财务管理</text>
        </view>
        <view class="service-item" @click="goToService('comments')">
          <uni-icons type="chat" size="24" color="#FF8C42"></uni-icons>
          <text>评价管理</text>
        </view>
        <view class="service-item" @click="goToService('statistics')">
          <uni-icons type="chart" size="24" color="#FF8C42"></uni-icons>
          <text>数据统计</text>
        </view>
        <view class="service-item" @click="goToService('settings')">
          <uni-icons type="gear" size="24" color="#FF8C42"></uni-icons>
          <text>店铺设置</text>
        </view>
      </view>
    </view>
    
    <!-- 商家工具 -->
    <view class="service-section">
      <view class="section-header">
        <text class="section-title">商家工具</text>
      </view>
      <view class="service-grid">
        <view class="service-item" @click="goToService('printer')">
          <uni-icons type="paperclip" size="24" color="#FF8C42"></uni-icons>
          <text>打印机</text>
        </view>
        <view class="service-item" @click="goToService('delivery')">
          <uni-icons type="map" size="24" color="#FF8C42"></uni-icons>
          <text>配送设置</text>
        </view>
        <view class="service-item" @click="goToService('customer')">
          <uni-icons type="headphones" size="24" color="#FF8C42"></uni-icons>
          <text>客服中心</text>
        </view>
        <view class="service-item" @click="goToService('feedback')">
          <uni-icons type="help" size="24" color="#FF8C42"></uni-icons>
          <text>意见反馈</text>
        </view>
        <view class="service-item" @click="goToService('about')">
          <uni-icons type="info" size="24" color="#FF8C42"></uni-icons>
          <text>关于我们</text>
        </view>
        <view class="service-item" @click="goToService('help')">
          <uni-icons type="help-filled" size="24" color="#FF8C42"></uni-icons>
          <text>帮助中心</text>
        </view>
      </view>
    </view>
    
    <!-- 商家详细信息弹窗 -->
    <view v-if="showDetailModal" class="modal-overlay" @click="closeMerchantDetail">
      <view class="merchant-detail-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">商家详细信息</text>
          <view class="close-btn" @click="closeMerchantDetail">
            <uni-icons type="close" size="20" color="#999"></uni-icons>
          </view>
        </view>
        
        <view class="modal-content" v-if="!isLoadingDetail">
          <view class="detail-section">
            <view class="detail-item">
              <text class="detail-label">商家名称：</text>
              <text class="detail-value">{{ merchantDetailInfo.name || '暂无' }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">用户名：</text>
              <text class="detail-value">{{ merchantDetailInfo.username || '暂无' }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">联系人：</text>
              <text class="detail-value">{{ merchantDetailInfo.contact || '暂无' }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">联系电话：</text>
              <text class="detail-value">{{ merchantDetailInfo.phone || '暂无' }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">地址：</text>
              <text class="detail-value">{{ merchantDetailInfo.address || '暂无' }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">状态：</text>
              <text class="detail-value" :class="merchantDetailInfo.status === 1 ? 'status-active' : 'status-inactive'">
                {{ formatStatus(merchantDetailInfo.status) }}
              </text>
            </view>
            <view class="detail-item">
              <text class="detail-label">创建时间：</text>
              <text class="detail-value">{{ formatDate(merchantDetailInfo.createTime) }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">更新时间：</text>
              <text class="detail-value">{{ formatDate(merchantDetailInfo.updateTime) }}</text>
            </view>
          </view>
        </view>
        
        <view class="loading-content" v-else>
          <text>加载中...</text>
        </view>
        
        <view class="modal-footer">
          <button class="edit-btn" @click="showEditModal">编辑</button>
          <button class="confirm-btn" @click="closeMerchantDetail">确认</button>
        </view>
      </view>
    </view>

    <!-- 编辑商家信息弹窗 -->
    <view v-if="showEditForm" class="modal-overlay" @click="closeEditModal">
      <view class="edit-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">编辑商家信息</text>
          <view class="close-btn" @click="closeEditModal">
            <uni-icons type="close" size="20" color="#999"></uni-icons>
          </view>
        </view>
        
        <scroll-view class="edit-content" scroll-y>
          <view class="edit-form">
            <view class="form-group">
              <text class="form-label">商家名称 *</text>
              <input 
                class="form-input" 
                v-model="editForm.name" 
                placeholder="请输入商家名称"
                maxlength="50"
              />
            </view>
            
            <view class="form-group">
              <text class="form-label">联系人</text>
              <input 
                class="form-input" 
                v-model="editForm.contact" 
                placeholder="请输入联系人姓名"
                maxlength="20"
              />
            </view>
            
            <view class="form-group">
              <text class="form-label">联系电话 *</text>
              <input 
                class="form-input" 
                v-model="editForm.phone" 
                placeholder="请输入联系电话"
                type="number"
                maxlength="11"
              />
            </view>
            
            <view class="form-group">
              <text class="form-label">地址</text>
              <textarea 
                class="form-textarea" 
                v-model="editForm.address" 
                placeholder="请输入详细地址"
                maxlength="200"
              ></textarea>
            </view>
            
            <view class="form-group">
              <text class="form-label">头像链接</text>
              <input 
                class="form-input" 
                v-model="editForm.avatarUrl" 
                placeholder="请输入头像链接（可选）"
              />
            </view>
            
            <!-- 头像预览 -->
            <view v-if="editForm.avatarUrl" class="avatar-preview">
              <text class="form-label">头像预览：</text>
              <image 
                class="preview-avatar" 
                :src="editForm.avatarUrl" 
                mode="aspectFill"
                @error="handleEditAvatarError"
              ></image>
            </view>

            <!-- 密码修改区域 -->
            <view class="password-section">
              <view class="section-divider">
                <text class="divider-text">修改密码（可选）</text>
              </view>
              
              <view class="form-group">
                <text class="form-label">原密码</text>
                <input 
                  class="form-input" 
                  v-model="editForm.oldPassword" 
                  placeholder="如需修改密码请输入原密码"
                  password
                  maxlength="20"
                />
              </view>
              
              <view class="form-group">
                <text class="form-label">新密码</text>
                <input 
                  class="form-input" 
                  v-model="editForm.newPassword" 
                  placeholder="请输入新密码"
                  password
                  maxlength="20"
                />
              </view>
              
              <view class="form-group">
                <text class="form-label">确认新密码</text>
                <input 
                  class="form-input" 
                  v-model="editForm.confirmNewPassword" 
                  placeholder="请再次输入新密码"
                  password
                  maxlength="20"
                />
              </view>
            </view>
          </view>
        </scroll-view>
        
        <view class="modal-footer">
          <button class="cancel-btn" @click="closeEditModal">取消</button>
          <button 
            class="update-submit-btn" 
            @click="handleUpdateMerchant"
            :disabled="isUpdating"
          >
            {{ isUpdating ? '更新中...' : '保存' }}
          </button>
        </view>
      </view>
    </view>

    <!-- 商家注册弹窗 -->
    <view v-if="showRegisterForm" class="modal-overlay" @click="closeRegisterModal">
      <view class="register-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">商家注册</text>
          <view class="close-btn" @click="closeRegisterModal">
            <uni-icons type="close" size="20" color="#999"></uni-icons>
          </view>
        </view>
        
        <scroll-view class="register-content" scroll-y>
          <view class="register-form">
            <view class="form-group">
              <text class="form-label">用户名 *</text>
              <input 
                class="form-input" 
                v-model="registerForm.username" 
                placeholder="请输入用户名"
                maxlength="20"
              />
            </view>
            
            <view class="form-group">
              <text class="form-label">密码 *</text>
              <input 
                class="form-input" 
                v-model="registerForm.password" 
                placeholder="请输入密码"
                password
                maxlength="20"
              />
            </view>
            
            <view class="form-group">
              <text class="form-label">确认密码 *</text>
              <input 
                class="form-input" 
                v-model="registerForm.confirmPassword" 
                placeholder="请再次输入密码"
                password
                maxlength="20"
              />
            </view>
            
            <view class="form-group">
              <text class="form-label">商家名称 *</text>
              <input 
                class="form-input" 
                v-model="registerForm.name" 
                placeholder="请输入商家名称"
                maxlength="50"
              />
            </view>
            
            <view class="form-group">
              <text class="form-label">联系人</text>
              <input 
                class="form-input" 
                v-model="registerForm.contact" 
                placeholder="请输入联系人姓名"
                maxlength="20"
              />
            </view>
            
            <view class="form-group">
              <text class="form-label">联系电话 *</text>
              <input 
                class="form-input" 
                v-model="registerForm.phone" 
                placeholder="请输入联系电话"
                type="number"
                maxlength="11"
              />
            </view>
            
            <view class="form-group">
              <text class="form-label">地址</text>
              <textarea 
                class="form-textarea" 
                v-model="registerForm.address" 
                placeholder="请输入详细地址"
                maxlength="200"
              ></textarea>
            </view>
            
            <view class="form-group">
              <text class="form-label">头像链接</text>
              <input 
                class="form-input" 
                v-model="registerForm.avatarUrl" 
                placeholder="请输入头像链接（可选）"
              />
            </view>
            
            <!-- 头像预览 -->
            <view v-if="registerForm.avatarUrl" class="avatar-preview">
              <text class="form-label">头像预览：</text>
              <image 
                class="preview-avatar" 
                :src="registerForm.avatarUrl" 
                mode="aspectFill"
                @error="handleAvatarError"
              ></image>
            </view>
          </view>
        </scroll-view>
        
        <view class="modal-footer">
          <button class="cancel-btn" @click="closeRegisterModal">取消</button>
          <button 
            class="register-submit-btn" 
            @click="handleRegister"
            :disabled="isRegistering"
          >
            {{ isRegistering ? '注册中...' : '注册' }}
          </button>
        </view>
      </view>
    </view>
    
    <!-- 退出登录按钮 (仅在登录状态显示) -->
    <view v-if="userStore.isLoggedIn && userStore.isMerchant()" class="logout-section">
      <button class="logout-btn" @click="handleLogout">退出登录</button>
    </view>
    
    <!-- 登录弹窗 -->
    <merchant-login-popup ref="loginPopupRef" @register="showRegisterModal"></merchant-login-popup>
    
    <!-- 用户类型管理 -->
    <user-type-manager></user-type-manager>
    
    <!-- 底部导航栏 -->
    <tab-bar :active="2"></tab-bar>
  </view>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import { useUserStore } from '@/store/user';
import UserTypeManager from '@/components/user-type-manager.vue';
import TabBar from '@/components/tab-bar.vue';
import LoginPopup from '@/components/login-popup.vue';
import { BASE_URL } from '@/config/env';
import { useRouter } from 'vue-router';


const userStore = useUserStore();
const statusBarHeight = ref(0);
const loginPopupRef = ref(null);

// 商家静态数据
const merchantData = reactive({
  orderCount: 128,
  productCount: 36,
  revenue: 9876.50,
  newOrderCount: 5
});

// 商家详细信息相关
const showDetailModal = ref(false);
const merchantDetailInfo = ref({});
const isLoadingDetail = ref(false);

// 商家注册相关
const showRegisterForm = ref(false);
const isRegistering = ref(false);
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  name: '',
  contact: '',
  phone: '',
  address: '',
  avatarUrl: ''
});

// 编辑商家信息相关
const showEditForm = ref(false);
const isUpdating = ref(false);
const editForm = reactive({
  name: '',
  contact: '',
  phone: '',
  address: '',
  avatarUrl: '',
  oldPassword: '',
  newPassword: '',
  confirmNewPassword: ''
});

// 显示编辑弹窗
const showEditModal = () => {
  // 填充当前商家信息到编辑表单
  editForm.name = merchantDetailInfo.value.name || '';
  editForm.contact = merchantDetailInfo.value.contact || '';
  editForm.phone = merchantDetailInfo.value.phone || '';
  editForm.address = merchantDetailInfo.value.address || '';
  editForm.avatarUrl = merchantDetailInfo.value.avatarUrl || '';
  editForm.oldPassword = '';
  editForm.newPassword = '';
  editForm.confirmNewPassword = '';
  
  showEditForm.value = true;
  showDetailModal.value = false; // 关闭详情弹窗
};

// 关闭编辑弹窗
const closeEditModal = () => {
  showEditForm.value = false;
};

// 处理编辑头像加载错误
const handleEditAvatarError = () => {
  uni.showToast({
    title: '头像链接无效',
    icon: 'none'
  });
};

// 验证编辑表单
const validateEditForm = () => {
  if (!editForm.name.trim()) {
    uni.showToast({
      title: '请输入商家名称',
      icon: 'none'
    });
    return false;
  }
  
  if (!editForm.phone.trim()) {
    uni.showToast({
      title: '请输入联系电话',
      icon: 'none'
    });
    return false;
  }
  
  // 验证手机号格式
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!phoneRegex.test(editForm.phone)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    });
    return false;
  }
  
  // 如果要修改密码，验证密码相关字段
  if (editForm.newPassword || editForm.confirmNewPassword || editForm.oldPassword) {
    if (!editForm.oldPassword.trim()) {
      uni.showToast({
        title: '请输入原密码',
        icon: 'none'
      });
      return false;
    }
    
    if (!editForm.newPassword.trim()) {
      uni.showToast({
        title: '请输入新密码',
        icon: 'none'
      });
      return false;
    }
    
    if (editForm.newPassword.length < 6) {
      uni.showToast({
        title: '新密码至少6个字符',
        icon: 'none'
      });
      return false;
    }
    
    if (editForm.newPassword !== editForm.confirmNewPassword) {
      uni.showToast({
        title: '两次新密码输入不一致',
        icon: 'none'
      });
      return false;
    }
  }
  
  return true;
};

// 处理更新商家信息
const handleUpdateMerchant = async () => {
  if (!validateEditForm()) {
    return;
  }
  
  if (!userStore.isLoggedIn || !userStore.token) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    return;
  }
  
  isUpdating.value = true;
  
  try {
    // 构建更新数据
    const updateData = {
      name: editForm.name.trim(),
      contact: editForm.contact.trim() || null,
      phone: editForm.phone.trim(),
      address: editForm.address.trim() || null,
      avatarUrl: editForm.avatarUrl.trim() || null
    };
    
    // 如果要修改密码，添加密码字段
    if (editForm.oldPassword && editForm.newPassword) {
      updateData.oldPassword = editForm.oldPassword;
      updateData.newPassword = editForm.newPassword;
    }
    
    console.log('更新商家信息请求数据:', updateData);
    
    const response = await uni.request({
      url: BASE_URL +'/api/merchant/info',
	  
      method: 'PUT',
      header: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${userStore.token}`
      },
      data: updateData
    });
    
    console.log('更新商家信息响应:', response);
    
    if (response.statusCode === 200 && response.data.code === 200) {
      uni.showToast({
        title: '信息更新成功！',
        icon: 'success'
      });
      
      // 关闭编辑弹窗
      closeEditModal();
      
      // 重新获取商家详细信息
      await fetchMerchantDetail();
      
      // 如果更新了头像，更新用户store中的信息
      if (updateData.avatarUrl && userStore.userInfo) {
        userStore.userInfo.avatar = updateData.avatarUrl;
      }
      
      // 如果更新了商家名称，更新用户store中的信息
      if (updateData.name && userStore.userInfo) {
        userStore.userInfo.shopName = updateData.name;
      }
      
    } else {
      uni.showToast({
        title: response.data.msg || '更新失败，请重试',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('更新商家信息失败:', error);
    uni.showToast({
      title: '网络错误，请稍后重试',
      icon: 'none'
    });
  } finally {
    isUpdating.value = false;
  }
};

// 显示注册弹窗
const showRegisterModal = () => {
  showRegisterForm.value = true;
  // 重置表单
  Object.assign(registerForm, {
    username: '',
    password: '',
    confirmPassword: '',
    name: '',
    contact: '',
    phone: '',
    address: '',
    avatarUrl: ''
  });
};

// 关闭注册弹窗
const closeRegisterModal = () => {
  showRegisterForm.value = false;
};

// 处理头像加载错误
const handleAvatarError = () => {
  uni.showToast({
    title: '头像链接无效',
    icon: 'none'
  });
};

// 验证注册表单
const validateRegisterForm = () => {
  if (!registerForm.username.trim()) {
    uni.showToast({
      title: '请输入用户名',
      icon: 'none'
    });
    return false;
  }
  
  if (registerForm.username.length < 3) {
    uni.showToast({
      title: '用户名至少3个字符',
      icon: 'none'
    });
    return false;
  }
  
  if (!registerForm.password.trim()) {
    uni.showToast({
      title: '请输入密码',
      icon: 'none'
    });
    return false;
  }
  
  if (registerForm.password.length < 6) {
    uni.showToast({
      title: '密码至少6个字符',
      icon: 'none'
    });
    return false;
  }
  
  if (registerForm.password !== registerForm.confirmPassword) {
    uni.showToast({
      title: '两次密码输入不一致',
      icon: 'none'
    });
    return false;
  }
  
  if (!registerForm.name.trim()) {
    uni.showToast({
      title: '请输入商家名称',
      icon: 'none'
    });
    return false;
  }
  
  if (!registerForm.phone.trim()) {
    uni.showToast({
      title: '请输入联系电话',
      icon: 'none'
    });
    return false;
  }
  
  // 验证手机号格式
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!phoneRegex.test(registerForm.phone)) {
    uni.showToast({
      title: '请输入正确的手机号',
      icon: 'none'
    });
    return false;
  }
  
  return true;
};

// 启用商家状态
const enableMerchantStatus = async (merchantId) => {
  try {
    console.log('正在启用商家状态，商家ID:', merchantId);
    
    // 调用管理员接口更新商家状态为1（启用）
    const response = await uni.request({
      url: BASE_URL +`/api/merchant/admin/${merchantId}/status`,
      method: 'PUT',
      header: {
        'Content-Type': 'application/json'
      },
      data: {
        status: 1 // 设置状态为启用
      }
    });
    
    console.log('启用商家状态响应:', response);
    
    if (response.statusCode === 200 && response.data.code === 200) {
      console.log('商家状态已成功启用');
      return true;
    } else {
      console.error('启用商家状态失败:', response.data.msg);
      return false;
    }
  } catch (error) {
    console.error('启用商家状态请求失败:', error);
    return false;
  }
};

// 处理商家注册
const handleRegister = async () => {
  if (!validateRegisterForm()) {
    return;
  }
  
  isRegistering.value = true;
  
  try {
    const response = await uni.request({
      url: BASE_URL +'/api/merchant/auth/register',
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      data: {
        username: registerForm.username.trim(),
        password: registerForm.password,
        confirmPassword: registerForm.confirmPassword,
        name: registerForm.name.trim(),
        contact: registerForm.contact.trim() || null,
        phone: registerForm.phone.trim(),
        address: registerForm.address.trim() || null,
        avatarUrl: registerForm.avatarUrl.trim() || null
      }
    });
    
    console.log('注册响应:', response);
    
    if (response.statusCode === 200 && response.data.code === 200) {
      const merchantData = response.data.data;
      
      // 注册成功后，自动启用商家状态
      if (merchantData && merchantData.id) {
        const statusEnabled = await enableMerchantStatus(merchantData.id);
        
        if (statusEnabled) {
          uni.showToast({
            title: '注册成功，账号已启用！',
            icon: 'success'
          });
        } else {
          uni.showToast({
            title: '注册成功，但账号启用失败，请联系管理员',
            icon: 'none',
            duration: 3000
          });
        }
      } else {
        uni.showToast({
          title: '注册成功！',
          icon: 'success'
        });
      }
      
      // 关闭注册弹窗
      closeRegisterModal();
      
      // 提示用户登录
      setTimeout(() => {
        uni.showModal({
          title: '注册成功',
          content: '注册成功，是否立即登录？',
          success: (res) => {
            if (res.confirm) {
              handleLogin();
            }
          }
        });
      }, 1500);
      
    } else {
      uni.showToast({
        title: response.data.msg || '注册失败，请重试',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('注册失败:', error);
    uni.showToast({
      title: '网络错误，请稍后重试',
      icon: 'none'
    });
  } finally {
    isRegistering.value = false;
  }
};

// 获取商家详细信息
const fetchMerchantDetail = async () => {
  if (!userStore.isLoggedIn || !userStore.token) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    return;
  }

  isLoadingDetail.value = true;
  
  try {
    const response = await uni.request({
      url: BASE_URL +'/api/merchant/info',
      method: 'GET',
      header: {
        'Authorization': `Bearer ${userStore.token}`
      }
    });
    
    console.log('商家详细信息响应:', response);
    
    if (response.statusCode === 200 && response.data.code === 200) {
      merchantDetailInfo.value = response.data.data;
      showDetailModal.value = true;
    } else {
      uni.showToast({
        title: response.data.msg || '获取商家信息失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取商家详细信息失败:', error);
    uni.showToast({
      title: '网络错误，请稍后重试',
      icon: 'none'
    });
  } finally {
    isLoadingDetail.value = false;
  }
};

// 显示商家详细信息
const showMerchantDetail = () => {
  fetchMerchantDetail();
};

// 关闭详细信息弹窗
const closeMerchantDetail = () => {
  showDetailModal.value = false;
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '暂无';
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  });
};

// 格式化状态
const formatStatus = (status) => {
  switch(status) {
    case 0: return '停用';
    case 1: return '启用';
    default: return '未知';
  }
};

// 获取状态栏高度
const getStatusBarHeight = () => {
  let systemInfo = null;
  try {
    systemInfo = uni.getSystemInfoSync();
    statusBarHeight.value = systemInfo.statusBarHeight || 0;
    console.log('状态栏高度:', statusBarHeight.value);
  } catch (e) {
    console.error('获取系统信息失败:', e);
    statusBarHeight.value = 0;
  }
};

// 手机号码脱敏
const maskPhone = (phone) => {
  if (!phone || phone.length < 11) return phone;
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
};

const handleLogin = () => {
  console.log('商家点击登录按钮');
  if (loginPopupRef.value) {
    loginPopupRef.value.open();
  } else {
    console.error('登录弹窗组件引用为空');
    uni.showToast({
      title: '登录功能暂不可用',
      icon: 'none'
    });
  }
};

// 处理退出登录
const handleLogout = () => {
  uni.showModal({
    title: '提示',
    content: '确认退出登录？',
    success: (res) => {
      if (res.confirm) {
        userStore.logout();
        uni.showToast({
          title: '已退出登录',
          icon: 'success'
        });
        
        // 退出后跳转到用户首页
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/index/index'
          });
        }, 500);
      }
    }
  });
};

// 查看全部订单
const viewAllOrders = () => {
  if (!userStore.isLoggedIn || !userStore.isMerchant()) {
    handleLogin();
    return;
  }
  
  uni.showToast({
    title: '订单管理功能开发中',
    icon: 'none'
  });
};

// 按类型查看订单
const viewOrderByType = (type) => {
  if (!userStore.isLoggedIn || !userStore.isMerchant()) {
    handleLogin();
    return;
  }
  
  const typeNames = {
    new: '新订单',
    processing: '处理中订单',
    shipping: '配送中订单',
    completed: '已完成订单',
    refund: '退款/售后'
  };
  
  uni.showToast({
    title: `${typeNames[type] || type}管理功能开发中`,
    icon: 'none'
  });
};

// 跳转到服务页面
const goToService = (service) => {
  if (!userStore.isLoggedIn || !userStore.isMerchant()) {
    handleLogin();
    return;
  }
  
  const serviceNames = {
    products: '商品管理',
    promotion: '促销活动',
    finance: '财务管理',
    comments: '评价管理',
    statistics: '数据统计',
    settings: '店铺设置',
    printer: '打印机设置',
    delivery: '配送设置',
    customer: '客服中心',
    feedback: '意见反馈',
    about: '关于我们',
    help: '帮助中心'
  };
  
  uni.showToast({
    title: `${serviceNames[service] || service}功能开发中`,
    icon: 'none'
  });
};

// 获取商家商品数量
const fetchMerchantProductCount = async () => {
  if (!userStore.isLoggedIn || !userStore.isMerchant()) {
    return;
  }
  
  try {
    const response = await uni.request({
      url: BASE_URL +'/api/merchant/products',
      method: 'GET',
      header: {
        'Authorization': `Bearer ${userStore.token || ''}`
      }
    });
    
    if (response.statusCode === 200 && response.data.code === 200) {
      if (Array.isArray(response.data.data)) {
        merchantData.productCount = response.data.data.length;
      }
    }
  } catch (error) {
    console.error('获取商家商品数量失败:', error);
  }
};

// 页面加载时执行
onMounted(() => {
  console.log('商家中心页面加载完成');
  userStore.initUserState();
  getStatusBarHeight();
  
  if (userStore.isLoggedIn && userStore.isMerchant()) {
    fetchMerchantProductCount();
  }
  
  if (userStore.isLoggedIn && !userStore.isMerchant()) {
    uni.showModal({
      title: '提示',
      content: '您当前是普通用户身份，是否切换为商家身份？',
      success: (res) => {
        if (res.confirm) {
          const merchantInfo = {
            id: 'M' + Math.floor(Math.random() * 10000),
            shopName: '示例商家店铺',
            phone: '13800138000',
            avatar: '/static/merchant-avatar.png'
          };
          userStore.login('merchant', merchantInfo);
          fetchMerchantProductCount();
        } else {
          uni.reLaunch({
            url: '/pages/index/index'
          });
        }
      }
    });
  }
});
</script>

<style>
.container {
  padding-bottom: 100rpx;
  background-color: #FFF9F2;
}

.merchant-info-section {
  background: linear-gradient(to right, #FF8C42, #FF9F1C);
  padding: 40rpx 30rpx;
  color: #fff;
  border-radius: 0 0 30rpx 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(255, 140, 66, 0.2);
}

.merchant-info {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  background-color: #fff;
  margin-right: 30rpx;
  border: 4rpx solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
}

.login-btn {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.register-btn {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.9);
  background-color: rgba(255, 255, 255, 0.2);
  padding: 8rpx 16rpx;
  border-radius: 12rpx;
  margin-bottom: 10rpx;
  display: inline-block;
  border: 1rpx solid rgba(255, 255, 255, 0.3);
  transition: all 0.3s ease;
}

.register-btn:active {
  background-color: rgba(255, 255, 255, 0.3);
  transform: scale(0.95);
}

.merchant-desc {
  font-size: 24rpx;
  opacity: 0.8;
}

.merchant-stats {
  display: flex;
  justify-content: space-around;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 16rpx;
  padding: 20rpx 0;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-num {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 6rpx;
}

.stat-label {
  font-size: 24rpx;
}

.order-section, .service-section {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #FFE6CC;
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  position: relative;
  padding-left: 20rpx;
}

.section-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 6rpx;
  height: 30rpx;
  background-color: #FF8C42;
  border-radius: 3rpx;
}

.view-all {
  display: flex;
  align-items: center;
  font-size: 24rpx;
  color: #999;
}

.order-types {
  display: flex;
  padding: 30rpx 0;
}

.order-type-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: transform 0.3s ease;
  position: relative;
}

.order-type-item:active {
  transform: scale(0.95);
}

.order-type-item text {
  font-size: 24rpx;
  margin-top: 10rpx;
  color: #666;
}

.badge {
  position: absolute;
  top: -5rpx;
  right: 20rpx;
  background-color: #FF4D4F;
  color: white;
  font-size: 20rpx;
  min-width: 32rpx;
  height: 32rpx;
  line-height: 32rpx;
  text-align: center;
  border-radius: 16rpx;
  padding: 0 6rpx;
}

.service-grid {
  display: flex;
  flex-wrap: wrap;
  padding: 20rpx 0;
}

.service-item {
  width: 33.33%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 0;
  transition: transform 0.3s ease;
}

.service-item:active {
  transform: scale(0.95);
}

.service-item text {
  font-size: 24rpx;
  margin-top: 10rpx;
  color: #666;
}

.merchant-name {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.merchant-id {
  font-size: 24rpx;
  opacity: 0.8;
}

.logout-section {
  padding: 30rpx 20rpx;
}

.logout-btn {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  font-size: 28rpx;
  color: #FF8C42;
  background-color: #fff;
  border: 1rpx solid #FF8C42;
  border-radius: 40rpx;
  transition: all 0.3s ease;
}

.logout-btn:active {
  background-color: #FFF0E0;
}

.merchant-detail-btn {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.9);
  background-color: rgba(255, 255, 255, 0.2);
  padding: 8rpx 16rpx;
  border-radius: 12rpx;
  margin-top: 10rpx;
  display: inline-block;
  border: 1rpx solid rgba(255, 255, 255, 0.3);
  transition: all 0.3s ease;
}

.merchant-detail-btn:active {
  background-color: rgba(255, 255, 255, 0.3);
  transform: scale(0.95);
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.merchant-detail-modal, .register-modal, .edit-modal {
  width: 90%;
  max-width: 600rpx;
  background-color: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.3);
  max-height: 80vh;
  display: flex;
  flex-direction: column;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background: linear-gradient(to right, #FF8C42, #FF9F1C);
  color: #fff;
  flex-shrink: 0;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
}

.close-btn {
  padding: 10rpx;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.2);
}

.modal-content, .edit-content {
  padding: 30rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.register-content {
  flex: 1;
  overflow-y: auto;
}

.register-form, .edit-form {
  padding: 30rpx;
}

.form-group {
  margin-bottom: 30rpx;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
  font-weight: 500;
}

.form-input {
  width: 100%;
  height: 80rpx;
  padding: 0 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  background-color: #fff;
  box-sizing: border-box;
}

.form-input:focus {
  border-color: #FF8C42;
  outline: none;
}

.form-textarea {
  width: 100%;
  min-height: 120rpx;
  padding: 15rpx 20rpx;
  border: 1rpx solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  background-color: #fff;
  box-sizing: border-box;
  resize: vertical;
}

.form-textarea:focus {
  border-color: #FF8C42;
  outline: none;
}

.avatar-preview {
  margin-top: 20rpx;
}

.preview-avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  border: 2rpx solid #ddd;
  margin-top: 10rpx;
}

.password-section {
  margin-top: 40rpx;
  padding-top: 30rpx;
  border-top: 1rpx solid #f0f0f0;
}

.section-divider {
  margin-bottom: 30rpx;
  text-align: center;
}

.divider-text {
  font-size: 26rpx;
  color: #666;
  background-color: #fff;
  padding: 0 20rpx;
  position: relative;
}

.divider-text::before {
  content: '';
  position: absolute;
  top: 50%;
  left: -100rpx;
  right: -100rpx;
  height: 1rpx;
  background-color: #e0e0e0;
  z-index: -1;
}

.loading-content {
  padding: 60rpx;
  text-align: center;
  color: #999;
}

.detail-section {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.detail-item {
  display: flex;
  align-items: flex-start;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.detail-item:last-child {
  border-bottom: none;
}

.detail-label {
  font-size: 28rpx;
  color: #666;
  min-width: 140rpx;
  font-weight: 500;
}

.detail-value {
  font-size: 28rpx;
  color: #333;
  flex: 1;
  word-break: break-all;
}

.status-active {
  color: #52c41a;
  font-weight: bold;
}

.status-inactive {
  color: #ff4d4f;
  font-weight: bold;
}

.modal-footer {
  padding: 20rpx 30rpx 30rpx;
  display: flex;
  justify-content: center;
  gap: 20rpx;
  flex-shrink: 0;
  border-top: 1rpx solid #f0f0f0;
}

.confirm-btn, .edit-btn {
  width: 120rpx;
  height: 70rpx;
  line-height: 70rpx;
  font-size: 28rpx;
  color: #fff;
  background: linear-gradient(to right, #FF8C42, #FF9F1C);
  border: none;
  border-radius: 35rpx;
  transition: all 0.3s ease;
}

.edit-btn {
  background: linear-gradient(to right, #1890ff, #40a9ff);
}

.confirm-btn:active, .edit-btn:active {
  transform: scale(0.95);
  opacity: 0.8;
}

.cancel-btn {
  width: 120rpx;
  height: 70rpx;
  line-height: 70rpx;
  font-size: 28rpx;
  color: #666;
  background-color: #f5f5f5;
  border: none;
  border-radius: 35rpx;
  transition: all 0.3s ease;
}

.cancel-btn:active {
  transform: scale(0.95);
  background-color: #e0e0e0;
}

.register-submit-btn, .update-submit-btn {
  width: 150rpx;
  height: 70rpx;
  line-height: 70rpx;
  font-size: 28rpx;
  color: #fff;
  background: linear-gradient(to right, #FF8C42, #FF9F1C);
  border: none;
  border-radius: 35rpx;
  transition: all 0.3s ease;
}

.register-submit-btn:disabled, .update-submit-btn:disabled {
  opacity: 0.6;
  background: #ccc;
}

.register-submit-btn:active:not(:disabled), .update-submit-btn:active:not(:disabled) {
  transform: scale(0.95);
  opacity: 0.8;
}
</style>